package org.finesys.common.log.trace.interceptor.mvc;

import lombok.extern.slf4j.Slf4j;
import org.finesys.common.log.trace.tracer.Tracer;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.finesys.common.log.constants.TraceConstants.*;

@Slf4j
public class SpringMvcInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getHeader(TRACE_ID);
        String spanId = request.getHeader(SPAN_ID);
        String parentId = request.getHeader(PARENT_ID);
        Tracer.trace(traceId, spanId, parentId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Tracer.remove();
    }
}
